/*
 * @Author: SamZhang samzhang@apjcorp.com
 * @Date: 2022-12-02 10:14:44
 * @LastEditors: SamZhang samzhang@apjcorp.com
 * @LastEditTime: 2023-02-16 15:03:54
 * @FilePath: /circulation-web/src/components/CatalogLink.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import * as React from "react";
import { Link } from "react-router";

interface CatalogLinkProps {
  url: string;
  title: string;
  label: string;
}

export default function CatalogLink({ url, title, label }: CatalogLinkProps) {
  const prepareBookUrl = (url): string => {
    const regexp = new RegExp(document.location.origin + "/(.*)/works/(.*)");
    const match = regexp.exec(url);
    if (match) {
      const library = match[1];
      const work = match[2];
      return encodeURIComponent(library + "/" + work);
    } else {
      return url;
    }
  };

  const pathFor = (bookUrl) => {
    const applocation_root = localStorage.getItem(
      "MOBEBR_CONFIG_APPLICATION_ROOT"
    );

    let path = applocation_root + "/admin/web";
    path += bookUrl ? `/book/${prepareBookUrl(bookUrl)}` : "";
    return path;
  };

  const finalBookUrl = pathFor(url);

  return (
    <Link
      to={finalBookUrl}
      title={title}
      target="_blank"
      className="btn inverted left-align small top-align"
    >
      {label}
    </Link>
  );
}
